import Food from './Food'
import Score from './Score'
import Snake from './Snake'

export default class Controls {
    food: Food
    score: Score
    snake: Snake

    direction: string = ''

    isLive = true;

    constructor() {
        this.food = new Food()
        this.score = new Score()
        this.snake = new Snake()

        this.init()
    }

    init() {
        document.addEventListener('keydown', this.onKeyDown.bind(this))
        this.onRun()
    }

    // 键盘按键
    onKeyDown(event: KeyboardEvent) {
        this.direction = event.key
    }

    onRun() {
        let X = this.snake.headX
        let Y = this.snake.headY
        switch (this.direction) {
            case 'ArrowUp':
            case 'up':
                console.log('Y-')
                Y -= 10
                break;
            case 'ArrowDown':
            case 'down':
                console.log('Y+')
                Y += 10
                break;
            case 'ArrowLeft':
            case 'left':
                console.log('X-')
                X -= 10
                break;
            case 'ArrowRight':
            case 'right':
                console.log('X+')
                X += 10
                break;
        }

        // // 重新赋值
        this.snake.headX = X
        this.snake.headY = Y

        this.isLive && setTimeout(this.onRun.bind(this), 300)
    }
} 